package com.putao.oauth.code.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.putao.oauth.code.service.IPhoneUserDetailService;
import com.putao.constants.OAuthConstant;
import com.putao.domain.SysRole;
import com.putao.domain.SysUser;
import com.putao.feign.UserFeign;
import com.putao.model.SecurityUser;
import com.putao.result.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/*
 @Author:putao
 @Date:2022-06-28 20:21:49
*/
@Service
public class PhoneUserDetailServiceImpl implements IPhoneUserDetailService {
    /**
     * 步骤一：创建一个类实现根据手机号码查询用户信息，如果不存在抛出异常提示用户
     */

    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByPhone(String phone, String code) throws UsernameNotFoundException {
        // 判断code是否已经过期，是否存在
        //String redisCode = redisService.get(VerifyCodeEnum.LOGIN_VERIFY_CODE.join(phone));
        //if (StringUtils.isBlank(code) || !code.equals(redisCode)) {
        //    throw new UsernameNotFoundException("验证码过期或者不存在");
        //}
        JsonResult<SysUser> phoneResult = userFeign.getByPhone(phone);
        if (!phoneResult.isSuccess()) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        SysUser user = phoneResult.getData();
        JsonResult<List<SysRole>> roleResult = userFeign.getRolesByRoleIds(user.getRoleIds());
        if (!roleResult.isSuccess()) {
            throw new UsernameNotFoundException("获取角色失败！");
        }
        List<String> roles = roleResult.getData().stream().map(sysRole -> OAuthConstant.ROLE_PREFIX + sysRole.getCode()).collect(Collectors.toList());
        return SecurityUser.builder()
                .id(user.getId())
                .username(user.getUsername())
                .avatar(user.getAvatar())
                .phone(user.getPhone())
                .email(user.getEmail())
                .password(user.getPassword())
                //将角色放入authorities中
                .authorities(AuthorityUtils.createAuthorityList(ArrayUtil.toArray(roles, String.class)))
                .build();
    }
}
